<?php

namespace App\Admin\Repositories;

use App\Models\AdminUser;
use App\Models\Project;
use App\Models\ProjectAgreement as Model;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

class AgreementRepository extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public function get(Grid\Model $model)
    {
        $dataWhere = null;
        $currLoginUser = Admin::user();
        $params = request()->input();

        $builder = DB::table('project_agreement as a');

        // 如果不是超级管理员和财务 数据需要筛选  如果是超级管理员、财务的话查询所有用户的协议
        if (!$currLoginUser->isAdministrator() && !$currLoginUser->isRole('finance')) {

            $dataWhere = function ($query) use ($currLoginUser) {

                // 如果是大区经理
                if ($currLoginUser->isRole('project-manager')) {
                    // 根据用户的公司id查询公司下所有的项目id
                    $project_id = Project::where('company_id', $currLoginUser->company_id)->pluck('id');
                    $query->whereIn('p.id', $project_id);
                }

                // 如果是区域经理  查看本区域下代理人创建的协议
                if ($currLoginUser->isRole('regional-supervisor')) {
                    // 查询代理人, 'admin_id' => $currLoginUser->id
                    $agent = AdminUser::where(['company_id' => $currLoginUser->company_id, 'region' => $currLoginUser->region, 'status' => 1])->pluck('id');
                    // 根据代理人查找对应用户
                    $userIds = User::whereIn('agent', $agent)->pluck('id');
                    // 查找对应用户的所有协议
                    $query->whereIn('user_id', $userIds);
                }
                // 如果是代理人的话查看自己创建的用户
                if ($currLoginUser->isRole('agent')) {
                    $userIds = User::where(['company_id' => $currLoginUser->company_id, 'agent' => $currLoginUser->id])->pluck('id');
                    $query->whereIn('user_id', $userIds);
                }

                $query->select('id')
                    ->from('project');
                // ->where('p.master_user_id', $currLoginUser->id)
                // ->orWhereRaw("FIND_IN_SET(" . $currLoginUser->id . ", p.worker_user_id)");
            };
        }
        if (isset($params['per_page']) && !empty($params['per_page'])) {
            $per_page = $params['per_page'];
        } else {
            $per_page = 20;
        }

        $builder->select([
            'p.project_name', 'p.project_sn', 'p.project_code', 'p.company_short', 'p.company as our_company',
            'p.active_name', 'p.sponsor', 'p.status as project_status',
            'a.*',
            'c.company_name',
            't.title as expense_type_title',
            'u.id_number', 'u.phone', 'u.payee_phone', 'u.unit'
        ])
            ->leftJoin('project as p', 'a.project_id', '=', 'p.id')
            ->leftJoin('company as c', 'p.company_id', '=', 'c.id')
            ->join('expense_type as t', 'a.fee_type_key', '=', 't.id')
            ->join('users as u', 'a.user_id', '=', 'u.id');

        return $builder->where($dataWhere)
            ->where(function (Builder $query) use ($params) {
                if (!empty($params['project_sn'])) {
                    $query->where('p.project_sn', $params['project_sn']);
                }
                if (!empty($params['agreement_code'])) {
                    $query->where('a.agreement_code', $params['agreement_code']);
                }
                if (!empty($params['active_name'])) {
                    $query->where('p.active_name', 'like', "%" . $params['active_name'] . "%");
                }
                if (!empty($params['active_date']['start'])) {
                    $query->where('a.active_date', '>=', $params['active_date']['start']);
                }
                if (!empty($params['active_date']['end'])) {
                    $query->where('a.active_date', '<=', $params['active_date']['end']);
                }

                if (!empty($params['project_id'])) {
                    $query->where('a.project_id', $params['project_id']);
                }
                if (!empty($params['pay_status'])) {
                    $query->where('a.pay_status', $params['pay_status']);
                }
            })
            ->orderBy('a.id', 'desc')
            ->paginate($per_page);
    }

    public static function getPayStatus()
    {
        return [
            0 => '待支付(待审核)',
            1 => '允许支付',
            2 => '已支付',
            -1 => '已驳回'
        ];
    }

    // 协议整体的审批流程
    public static function getFlowMap()
    {
        return [
            1 => 'audit_first', // 协议审核
            2 => 'audit_fee', // 劳务审核
        ];
    }

    public static function getAuditStatus($index = '')
    {
        $map = [
            'audit_fee' => [0 => '待审核', 1 => '通过', -1 => '驳回'],
            'audit_first' => [0 => '待审核', 1 => '通过', -1 => '驳回'],
        ];
        return $map[$index] ?? [];
    }
}
